package com.android.museum.view

import android.animation.AnimatorListenerAdapter
import android.animation.ValueAnimator
import android.content.Context
import android.util.AttributeSet
import android.util.Log
import android.view.LayoutInflater
import android.view.animation.AccelerateDecelerateInterpolator
import android.widget.FrameLayout
import com.android.museum.R

class MuseumContentView @JvmOverloads constructor(
    context: Context, attributeSet: AttributeSet? = null, defStyle: Int = 0
) : FrameLayout(context, attributeSet, defStyle) {
    private var mAnimator: ValueAnimator? = null
    private val mRatio = 0.3f
    private var mDisplayView: ProductDisplayView
    private var mDescriptionView: ProductDescriptionView

    init {
        LayoutInflater.from(context).inflate(R.layout.museum_content_view, this)
        mDisplayView = findViewById(R.id.product_display_view)
        mDescriptionView = findViewById(R.id.product_description_view)
        post {
            mDescriptionView.y = height.toFloat()
        }
    }

    fun showDisplayView() {
        if (mAnimator?.isRunning == true) {
            return
        }

        if (mDisplayView.y >= 0f) {
            return
        }
        mAnimator = ValueAnimator.ofFloat(0f, 1f)
        mAnimator?.interpolator = AccelerateDecelerateInterpolator()
        mAnimator?.duration = 200
        mAnimator?.addUpdateListener(object : AnimatorListenerAdapter(), ValueAnimator.AnimatorUpdateListener {
            override fun onAnimationUpdate(animation: ValueAnimator) {
                val fraction = animation.animatedFraction
                mDisplayView.y = -(height * mRatio) * (1 - fraction)
                mDescriptionView.y = (height * mRatio) + height * (fraction * (1 - mRatio))
            }
        })
        mAnimator?.start()
        Log.i("wll", "showDisplayView")
    }

    fun showDescriptionView() {
        if (mAnimator?.isRunning == true) {
            return
        }

        if (mDisplayView.y < 0f) {
            return
        }

        mAnimator = ValueAnimator.ofFloat(0f, 1f)
        mAnimator?.interpolator = AccelerateDecelerateInterpolator()
        mAnimator?.duration = 200
        mAnimator?.addUpdateListener(object : AnimatorListenerAdapter(), ValueAnimator.AnimatorUpdateListener {
            override fun onAnimationUpdate(animation: ValueAnimator) {
                val fraction = animation.animatedFraction
                mDisplayView.y = -(height * mRatio) * fraction
                mDescriptionView.y = height - height * (1 - mRatio) * fraction
            }
        })
        mAnimator?.start()
        Log.i("wll", "showDescriptionView")
    }

    override fun onDetachedFromWindow() {
        super.onDetachedFromWindow()
        mAnimator?.cancel()
        mAnimator = null
    }
}